package johmap;

import static java.lang.String.format;

import javax.jws.WebService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.googlecode.johmap.decisionmaker.Decisionmaker;
import com.googlecode.johmap.image.TableImageBo;
import com.googlecode.johmap.image.TableImageDecisionBo;

@WebService(endpointInterface = "johmap.Johmap")
public class JohmapImpl implements Johmap {

    @Autowired
    private TableImageBo tableImageBo;

    private Decisionmaker decisionmaker;
    protected final Logger logger = LoggerFactory.getLogger(getClass());


    @Override
    public SaveTableImageOutput saveTableImage(SaveTableImageInput inputImage) {

        // Set key variables
        SaveTableImageOutput output = null;
        tableImageBo = null;
        TableImageDecisionBo decisionBoIn = null;

        // TODO - build an observer

        Tableimage imageIn = inputImage.getTableImageIn();
        if (imageIn != null) {
            tableImageBo.setImage(imageIn);
            tableImageBo.log();
            tableImageBo.notifyObservers();
        }

        Tableimagedecision decision = inputImage.getPreviousDecision();
        if (decision != null) {
            decisionBoIn = new TableImageDecisionBo(decision);
            decisionBoIn.log();
        }

        try {
            decision = decisionmaker.makeDecision(tableImageBo, decisionBoIn);
        }
        // handle instances of no decision maker present
        catch (NullPointerException nullPointerException) {
            decision = getBaseDecision();
            logger.error(format("FATAL: DecisionMaker not present"));

            // TODO - Enable exception
            // throw new DecisionMakerNotPresentException();
        }
        output = new SaveTableImageOutput();
        output.setTableImageIn(imageIn);
        output.setTableImageDecision(decision);

        return output;
    }

    private Tableimagedecision getBaseDecision() {

        Tableimagedecision decision = new Tableimagedecision();
        decision.setBet(11d);
        decision.setWait(500);
        return decision;
    }

    // TODO - use spring to wire this in
    public void setDecisionmaker(Decisionmaker decisionmaker) {
        this.decisionmaker = decisionmaker;
    }

    public TableImageBo getTableImageBo() {
        return tableImageBo;
    }

    public void setTableImageBo(TableImageBo tableImageBo) {
        this.tableImageBo = tableImageBo;
    }


    // TODO - plug c++ component into the Maven structure...

}
